package com.auditlog.boot.aop.datasource;

import com.auditlog.datasource.ConnectionProxy;
import com.auditlog.datasource.context.ContextHolder;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

import java.lang.reflect.Method;
import java.sql.Connection;

/**
 *
 * @author Zhiyang.Zhang
 * @date 2022/12/6 9:33
 * @version 1.0
 */
public class ConnectionMethodInterceptor implements MethodInterceptor {

    private ConnectionProxy connectionProxy;

    public ConnectionMethodInterceptor(ConnectionProxy connectionProxy) {
        this.connectionProxy = connectionProxy;
    }

    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        Method targetMethod = invocation.getMethod();
        String name = targetMethod.getName();
        if (!ContextHolder.getExecuteContext().isAudit()) {
            Method declaredMethod;
            try {
                declaredMethod = Connection.class.getDeclaredMethod(name, targetMethod.getParameterTypes());
            } catch (NoSuchMethodException e) {
                return invocation.proceed();
            }
            Connection connection = connectionProxy.getTargetConnection();
            return declaredMethod.invoke(connection, invocation.getArguments());
        }
        return invocation.proceed();
    }
}
